package com.inossem.utils.request;

import android.content.Context;
import android.graphics.Bitmap;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.inossem.utils.base.Utils;
import com.inossem.utils.log.LogUtils;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.UUID;

/**
 * Created by leij on 2017/6/5.
 */

public class VolleyUtils {

    private static final String URL = "url:";

    private static final String METHOD = "method:";

    private static final String HEADER = "header:";

    private static final String BODY = "body:";

    private static final String REQUEST = "【request】";

    private static RequestQueue requestQueue;

    // 请求设置
    private static DefaultRetryPolicy defaultRetryPolicy = new DefaultRetryPolicy(
            DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4 * 6, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

    /**
     * 获取请求队列
     *
     * @param context 上下文
     * @return 返回请求队列
     * @author leij
     */
    public synchronized static RequestQueue getRequestQueue(Context context) {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        }
        return requestQueue;
    }

    public synchronized static boolean addRequest(Context context, Request<?> request) {
        boolean result = false;
        if (request != null) {
            RequestQueue requestQueue = getRequestQueue(context);
            requestQueue.add(request);
            try {
                String url = request.getUrl();
                String method = getMethodStr(request.getMethod());
                String body = "";
                String header = "";
                if (request.getHeaders() != null) {
                    Map<String, String> headerMap = request.getHeaders();
                    for (String key : headerMap.keySet()) {
                        header = header + "【" + key + "】=【" + headerMap.get(key) + "】   ";
                    }
                }
                if (request.getBody() != null) {
                    body = new String(request.getBody(), "UTF-8");
                }
                LogUtils.logRequestI(context, REQUEST + "\n" + URL + url + "\n" + METHOD + method + "\n" + HEADER + header + "\n" + BODY + body);
//                LogUtils.logRequestI(context, REQUEST + "\n" + URL + url + "\n" + METHOD + method + "\n" + BODY + body);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (AuthFailureError authFailureError) {
                authFailureError.printStackTrace();
            }

            result = true;
        }
        return result;
    }

    private static String getMethodStr(int method) {
        String result = "UNKNOWN";
        switch (method) {
            case Request.Method.GET:
                result = "GET";
                break;
            case Request.Method.POST:
                result = "POST";
                break;
            case Request.Method.PUT:
                result = "PUT";
                break;
            case Request.Method.DELETE:
                result = "DELETE";
                break;
        }
        return result;
    }

    /**
     * 获取ImageLoader对象,将返回图片转换成圆角形式
     *
     * @param queue  请求序列
     * @param pixels 圆角尺寸
     * @return ImageLoader对象
     */
    public static ImageLoader getImageLoader(RequestQueue queue, final int pixels) {
        return new ImageLoader(queue, LruImageCache.instance()) {

            @Override
            protected void onGetImageSuccess(String cacheKey, Bitmap response) {
                response = Utils.toRoundCorner(response, pixels);
                super.onGetImageSuccess(cacheKey, response);
            }
        };
    }

    /**
     * 获取ImageLoader对象
     *
     * @param queue 请求序列
     * @return ImageLoader对象
     */
    public static ImageLoader getImageLoader(RequestQueue queue) {
        return new ImageLoader(queue, LruImageCache.instance());
    }

    public static JsonObjectRequest requestJson(final Context context, int method, String url, final Map<String, String> headers, final String params, boolean https, final VolleyListener<String> volleyListener) {
        if (https) {
            // 设置信任所有证书
            SsX509TrustManager.allowAllSSL();
        }
        JsonObjectRequest request = new JsonObjectRequest(method, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                volleyListener.onSuccess(response.toString(), volleyListener.getResponseHeaders());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyListener.onError(error);
            }
        }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers == null) {
                    return super.getHeaders();
                } else {
                    return headers;
                }
            }

            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                volleyListener.setResponseHeaders(response.headers);
                return super.parseNetworkResponse(response);
            }
        };
        // 设置超时时间10秒，默认2.5秒
        request.setRetryPolicy(defaultRetryPolicy);
        request.setTag(UUID.randomUUID().toString());// 设置TAG值
        return request;
    }


    public static StringRequest requestString(final Context context, int method, String url, final Map<String, String> headers, final Map<String, String> params, boolean https, final VolleyListener<String> volleyListener) {
        if (https) {
            // 设置信任所有证书
            SsX509TrustManager.allowAllSSL();
        }
        StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                volleyListener.onSuccess(response, volleyListener.getResponseHeaders());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyListener.onError(error);
            }

        }) {
            // 需要重写获取参数的函数,可以向服务器提交参数
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                if (params == null) {
                    return super.getParams();
                } else {
                    return params;
                }
            }

            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers == null) {
                    return super.getHeaders();
                } else {
                    return headers;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                volleyListener.setResponseHeaders(response.headers);
                return super.parseNetworkResponse(response);
            }

        };
        // 设置超时时间10秒，默认2.5秒
        request.setRetryPolicy(defaultRetryPolicy);
        request.setTag(UUID.randomUUID().toString());// 设置TAG值
        return request;
    }

}
